/**
 *
 */
package com.teamall.web.sys.service.impl;

import com.teamall.core.common.Page;
import com.teamall.core.convert.IArgConversionService;
import com.teamall.core.idproduce.ISequenceGenerator;
import com.teamall.framework.exception.BaseAppException;
import com.teamall.framework.log.LogManager;
import com.teamall.framework.util.BeanUtils;
import com.teamall.framework.util.IdCreateUtils;
import com.teamall.framework.util.Utils;
import com.teamall.web.app.db.dao.AppCommonDao;
import com.teamall.web.app.vo.AppUserVO;
import com.teamall.web.family.db.dao.FamilyInfoDao;
import com.teamall.web.family.db.dao.FamilyReplyDao;
import com.teamall.web.sys.db.arg.SysUserArg;
import com.teamall.web.sys.db.dao.SysUserDao;
import com.teamall.web.sys.db.dao.SysUserTokenDao;
import com.teamall.web.sys.db.po.SysUserPO;
import com.teamall.web.sys.db.po.SysUserTokenPO;
import com.teamall.web.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <Description> <br>
 *
 * @author codeCreater<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2014年11月11日 <br>
 * @see com.teamall.web.sys.service.impl <br>
 * @since V1.0<br>
 */

@Service("sysUserService")
public class SysUserServiceImpl implements ISysUserService {


    private static final LogManager logger = LogManager
            .getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserTokenDao sysUserTokenDao;
    @Autowired
    private FamilyReplyDao familyReplyDao;
    @Autowired
    private AppCommonDao appCommonDao;
    @Autowired
    private FamilyInfoDao familyInfoDao;
    /**
     * 查询条件转换成Arg类的服务接口A
     */
    @Resource(name = "defaultArgConversionService")
    private IArgConversionService argConversionService;

    /**
     * 主键生成器
     */
    @Resource(name = "sequenceProcGenerator")
    private ISequenceGenerator sequenceGenerator;


    @Override
    public SysUserPO selectByPrimaryKey(Integer key) throws BaseAppException {
        // ///////
        // TODO 根据业务场景，设置查询条件、数据校验等

        // ///////
        return sysUserDao.selectByPrimaryKey(key);
    }

    @Override
    public List<SysUserPO> selectByArg(SysUserPO record) throws BaseAppException {
        logger.debug("selectByArg begin...record={0}", record);

        // 第一种方式：自己创建arg，自行设置查询条件及操作符
        SysUserArg arg = new SysUserArg();
        SysUserArg.SysUserCriteria criteria = arg.createCriteria();
        // TODO 根据业务场景，设置查询条件，示例
        if (Utils.notEmpty(record.getLoginName())) {
            criteria.andLoginNameEqualTo(record.getLoginName());
        }
        if (Utils.notEmpty(record.getPassword())) {
            criteria.andPasswordEqualTo(record.getPassword());
        }
        if (Utils.notEmpty(record.getUserObjType())) {
            criteria.andUserObjTypeEqualTo(record.getUserObjType());
        }
        return sysUserDao.selectByArg(arg);
    }

    @Override
    public Page<SysUserPO> selectByArgAndPage(SysUserPO record, Page<SysUserPO> resultPage)
            throws BaseAppException {
        logger.debug("selectByArgAndPage begin...record={0}", record);

        // 第一种方式：自己创建arg，自行设置查询条件及操作符
        // SysUserArg arg = new SysUserArg();
        // //TODO 根据业务场景，设置查询条件，示例
        // SysUserCriteria criteria = arg.createCriteria();
        // if (Utils.notEmpty(record.getUserName())) {
        // criteria.andUserNameLike(record.getUserName());
        // }

        // 第二种方式：利用arg转换服务，转换出arg，带上查询条件及操作符，
        // 转换后，还可以自行对arg进行设置修改
        SysUserArg arg = argConversionService.invokeArg(SysUserArg.class, record);

        resultPage = sysUserDao.selectByArgAndPage(arg, resultPage);


        return resultPage;
    }

    @Override
    public int add(SysUserPO record) throws BaseAppException {
        logger.debug("add begin...record={0}", record);

        // ///////
        // TODO 根据业务场景，进行重名校验、设置主键、设置属性默认值等
        // 获取主键
        // int pkId = sequenceGenerator.sequenceIntValue("表名","主键名");
        // record.setUserId(pkId);
        // record.setCreatedDate(new Date());
        // ///////

        return sysUserDao.insertSelective(record);
    }

    @Override
    public int update(SysUserPO record) throws BaseAppException {
        logger.debug("update begin...record={0}", record);

        // ///////
        // TODO 根据业务场景，进行重名校验、数据有效性校验、设置属性默认值等

        // ///////

        return sysUserDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public int delete(SysUserPO record) throws BaseAppException {
        logger.debug("delete begin...record={0}", record);

        // ///////
        // TODO 根据业务场景，进行关联性校验、关联删除等

        // ///////

        return sysUserDao.deleteByPrimaryKey(record.getUserId());
    }

    @Override
    public AppUserVO userLogin(String liginName) throws BaseAppException {
        AppUserVO appUserVO = new AppUserVO();
        SysUserPO sysUserPO = new SysUserPO();
        sysUserPO.setLoginName(liginName);
        List<SysUserPO> sysUserPOList = this.selectByArg(sysUserPO);
        if (sysUserPOList.size() > 0) {
            SysUserPO resultPO = sysUserPOList.get(0);
            BeanUtils.copyProperties(resultPO, appUserVO);
            String token = IdCreateUtils.createId();
            SysUserTokenPO sysUserTokenPO = new SysUserTokenPO();
            sysUserTokenPO.setToken(token);
            sysUserTokenPO.setUserId(resultPO.getUserId());
            sysUserTokenPO.setCreateDate(new Date());
            sysUserTokenDao.insert(sysUserTokenPO);
            appUserVO.setToken(token);
            appUserVO.setUserId(resultPO.getUserObjId());
            appUserVO.setTownId(resultPO.getTownId());
            appUserVO.setVillageId(resultPO.getVillageId());
            return appUserVO;
        } else {
            return null;
        }
    }
    @Override
    public AppUserVO userLogin(String loginName, String password, Integer userObjType) throws BaseAppException {
        AppUserVO appUserVO = new AppUserVO();
        SysUserPO sysUserPO = new SysUserPO();
        sysUserPO.setLoginName(loginName);
        sysUserPO.setPassword(password);
        sysUserPO.setUserObjType(userObjType);
        List<SysUserPO> sysUserPOList = this.selectByArg(sysUserPO);
        if (sysUserPOList.size() > 0) {
            SysUserPO resultPO = sysUserPOList.get(0);
            BeanUtils.copyProperties(resultPO, appUserVO);
            String token = IdCreateUtils.createId();
            SysUserTokenPO sysUserTokenPO = new SysUserTokenPO();
            sysUserTokenPO.setToken(token);
            sysUserTokenPO.setUserId(resultPO.getUserId());
            sysUserTokenPO.setCreateDate(new Date());
            sysUserTokenDao.insert(sysUserTokenPO);
            appUserVO.setToken(token);
            appUserVO.setUserId(resultPO.getUserId());
            Integer familyId = appCommonDao.qryFamilyMemberByUserObjId(resultPO.getUserObjId());
            appUserVO.setFamilyId(familyId);
            return appUserVO;
        } else {
            return null;
        }
    }

    @Override
    public String updPassword(Integer userId, String oldPassword, String newPassword) throws BaseAppException {
        SysUserPO sysUserPO = this.selectByPrimaryKey(userId);
        if (Utils.isEmpty(sysUserPO)) {
            return "-1";
        } else {
            if (sysUserPO.getPassword().equals(oldPassword)) {
                String token = IdCreateUtils.createId();
                SysUserTokenPO sysUserTokenPO = new SysUserTokenPO();
                sysUserTokenPO.setToken(token);
                sysUserTokenPO.setUserId(sysUserPO.getUserId());
                sysUserTokenPO.setCreateDate(new Date());
                sysUserTokenDao.insert(sysUserTokenPO);
                sysUserPO.setPassword(newPassword);
                this.update(sysUserPO);
                return token;
            } else {
                return "-2";
            }
        }
    }

    @Override
    public String updPassword(String userName, String oldPassword, Integer userObjType, String newPassword) throws BaseAppException {
        SysUserPO sysUserPO = new SysUserPO();
        sysUserPO.setLoginName(userName);
        sysUserPO.setPassword(oldPassword);
        sysUserPO.setUserObjType(userObjType);
        List<SysUserPO> sysUserPOList = this.selectByArg(sysUserPO);
        if (Utils.isEmpty(sysUserPOList)) {
            return "-1";
        } else {
            SysUserPO resultPo = sysUserPOList.get(0);
            if (resultPo.getPassword().equals(oldPassword)) {
                String token = IdCreateUtils.createId();
                SysUserTokenPO sysUserTokenPO = new SysUserTokenPO();
                sysUserTokenPO.setToken(token);
                sysUserTokenPO.setUserId(resultPo.getUserId());
                sysUserTokenPO.setCreateDate(new Date());
                sysUserTokenDao.insert(sysUserTokenPO);
                resultPo.setPassword(newPassword);
                this.update(resultPo);
                return token;
            } else {
                return "-2";
            }
        }
    }

    @Override
    public Integer getAidMainStaffByUserObjId(Integer userObjId) throws BaseAppException {
        Integer familyId = appCommonDao.qryFamilyMemberByUserObjId(userObjId);
        Integer aidMainStaff = appCommonDao.qryAidMainStaffbyFamilyId(familyId);
        return aidMainStaff;
    }
}
